package cn.edu.hit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by Wang on 2018/11/15.
 */
public class CachedObjectPool<K, V> implements ICachedObjectPool<K, V> {
    private Queue<K> keyStack;
    private Map<K, V> valueMap;
    private List<V> valueList;
    private int cacheSize = 2;

    public CachedObjectPool(int cacheSize) {
        this.cacheSize = cacheSize > 0 ? cacheSize : 1;
        keyStack = new SynchronousQueue<>();
        valueMap = new ConcurrentHashMap<>();
    }

    @Override
    public synchronized void push(K key, V value) {
        if (valueMap.containsKey(key)) {
            valueMap.put(key, value);
        } else {
            while (keyStack.size() > cacheSize) {
                K k = keyStack.poll();
                valueMap.remove(k);
            }

            keyStack.offer(key);
            valueMap.put(key, value);
        }
    }

    @Override
    public V get(K key) {
        return valueMap.get(key);
    }

    @Override
    public V get(K key, V defaultValue) {
        if (valueMap.containsKey(key))
            return valueMap.get(key);
        else
            return defaultValue;
    }

    @Override
    public boolean has(K unitId) {
        return valueMap.containsKey(unitId);
    }

    @Override
    public List<V> vals(K key) {

        return valueList;
    }
}
